//
//  MyHttpServer.m
//  LocalWebServerDemo
//
//  Created by yg lin on 2018/4/3.
//  Copyright © 2018年 ymtx. All rights reserved.
//

#import "MyHttpServer.h"
#import "HTTPServer.h"
#import "MyHTTPConnection.h"

@interface MyHttpServer()

@end

@implementation MyHttpServer

+ (MyHttpServer *)shared {
    static id p_instance = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        p_instance = [[self alloc] init];
    });
    return p_instance;
}

- (id)init {
    if (self = [super init]) {
        /* 默认端口号 */
        self.defaultPort = 15159;
    }
    return self;
}

/* 开启服务器 */
- (void)startServer
{
    _httpServer = [[HTTPServer alloc] init];
    [_httpServer setType:@"_http._tcp."];
    [_httpServer setConnectionClass:[MyHTTPConnection class]];
    NSString *webPath = [[NSBundle mainBundle] resourcePath];
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if (![fileManager fileExistsAtPath:webPath]){
        NSLog(@"File path error!");
    }else{
        NSString *webLocalPath = webPath;
        [_httpServer setDocumentRoot:webLocalPath];
    }
    [_httpServer setPort:self.defaultPort];
    if (![_httpServer isRunning]) {
        NSError *error;
        if([_httpServer start:&error])
        {
            NSLog(@"启动成功 port %d %@", [_httpServer listeningPort], [_httpServer publishedName]);
            [AppContext sharedContext].isStatus = @"1";
        }
        else
        {
            NSLog(@"启动失败");
            [AppContext sharedContext].isStatus = @"0";
        }
    }
    else {
        NSLog(@"httpServer isRunning");
        [AppContext sharedContext].isStatus = @"0";
    }
}

#pragma mark -- 配置路由
- (void)setupRoutes {

}

/* 停止本地服务器 */
- (void)stopServer {
    if (self.httpServer) {
        [_httpServer stop];
        _httpServer = nil;
    }
}


@end
